home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5627 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: nntp.crl.com!tdd!dennis.weaver
  2. Distribution: world
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Borland C++ 4.5 : delete [] operator - what's goin
  5. From: dennis.weaver@datadim.com (Dennis Weaver)
  6. Message-ID: <1e8.123566.283@datadim.com>
  7. Date: Mon,  5 Feb 96 17:35:00 +0000
  8. Organization: TDD -- The Data Dimension -- Duluth, GA -- 404-495-9479
  9.  
  10. History:
  11. >HI,
  12. >I'm using EasyWin (Borland C++ 4.5) to test my matrix library under
  13. Windows
  14. 3.1.
  15. >Could anybody tell me what's wrong in the following code?
  16. >
  17. >template<class T> class TMatrix
  18. >{
  19. >  public:
  20. >        TMatrix(size_t m = 0, size_t n = 0);
  21. > ~TMatrix()
  22. >                {
  23. >  delete[] elem;
  24. >  delete[] pcol;
  25. >         }
  26. >        T& operator()(size_t i, size_t j);
  27. >  {
  28. >  return pcol[j][i];
  29. >  }
  30. >
  31. >          //....
  32. >  private:
  33. >        size_t nrow;
  34. >        size_t ncol;
  35. >        T**    pcol;           // pointer to columns
  36. >        T*     elem;           // element array
  37. >};
  38. >
  39. >template<class T>
  40. >TMatrix<T>::TMatrix(size_e m, size_t n) : nrow(m), ncol(n)
  41. >{
  42. >        elem = new T[m*n+1];  //  a dummy space for efficient use
  43. >        pcol = new T*[n+1];   //  of 1-based indexing
  44. >
  45. > if (n > 0)
  46. > {
  47. >  pcol[1] = elem;
  48. >  for (int i=1; i <= n; i++)
  49. >   pcol[i+1] = pcol[i] + m;
  50. > }
  51. >}
  52. >
  53. >typedef TMatrix<double> Matrix;
  54. >
  55. >void test()
  56. >{
  57. > Matrix a(4,4);
  58. > for (int i = 1; i <= 4; i++)
  59. >  for (int j = 1; j <= 4; j++)
  60. >   a(i,j) = i + j;
  61. >}
  62. >
  63. The destructor is going to delete the whole array, from index
  64. 0 through 4 (it doesn't know you're trying to make a 1-based
  65. index). Your pcol[i+1] = pcol[i] + m code did not initialize
  66. index 0 (you started with pcol[1] = elem).  It looks like
  67. delete[] pcol is trying to free a NULL pointer at pcol[0].
  68. That's my best guess.
  69.